package cn.jdemo.pattern.mutex.cas;

import cn.jdemo.pattern.mutex.Lock;
import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 自旋锁 互斥锁
 * @description
 * @date 2021/1/28
 */
public class CAS implements Lock {
    static Unsafe unsafe;
    static AtomicReference atomicReference = new AtomicReference();

    @Override
    public void acquire() throws InterruptedException {
        // unsafe.compareAndSwapObject(null,1000 , null,null ); 直接使用unsafe比较麻烦
        while(!atomicReference.compareAndSet(null,Thread.currentThread())){
        }
    }

    @Override
    public void release() {
        while (!atomicReference.compareAndSet(Thread.currentThread(), null)){
        }
    }

    static {
        // unsafe = Unsafe.getUnsafe();// 不受信任,无法获取
        Class<Unsafe> unsafeClass = Unsafe.class;
        try {
            Field theUnsafe = unsafeClass.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            unsafe = (Unsafe) theUnsafe.get(null);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }


}
